package com.macbulldev.poc.testgin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.PolicyForm;
import com.macbulldev.poc.testgin.domain.PolicyType;
import com.macbulldev.poc.testgin.domain.Rate;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.domain.TransactionQuestion;
import com.macbulldev.poc.testgin.domain.TrialGroup;
import com.macbulldev.poc.testgin.domain.Underwriter;
import com.macbulldev.poc.testgin.importer.ImportBuilder;
import com.macbulldev.poc.testgin.service.WebappUtils;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "scenario", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.Scenario.class)
@org.springframework.web.bind.annotation.RequestMapping("/scenario/**")
@org.springframework.stereotype.Controller
public class ScenarioController {
	
	
	private static final Logger LOGGER = Logger.getLogger(ScenarioController.class);
	
	
	/*** Owner Lists *****/
	@RequestMapping(value = "/scenario/manual_show", method = RequestMethod.POST)    
    public String renderManualShow(@RequestParam(value = "scenarioId", required = false) Long id,ModelMap modelMap) {
		
		LOGGER.debug("Show Scenario:  "+id);
		
		
		modelMap.addAttribute("scenario",Scenario.findScenario(id));
        return "scenario/manual_show";        
    }
	
	@RequestMapping(value = "/scenario/{policyType}/list", method = RequestMethod.GET)    
    public String renderOwnerBasicList(@PathVariable("policyType") String policyType, @RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {
		int sizeNo = 20;           
        int pageNumber = page == null ? 0 : page;
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        modelMap.addAttribute("scenarios",Scenario.findScenarioByPolicyTypeAbbrName(policyType, pageNumber*sizeNo, sizeNo));
        modelMap.addAttribute("policyType", PolicyType.findPolicyTypeByAbbrName(policyType));
        Long count = Scenario.countScenarios();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        return "scenario/list";        
    }
	
	@RequestMapping(value = "/scenario/filter", method = RequestMethod.GET)    
    public String renderScenarioFilteredList(@RequestParam(value = "policyType", required = false) String policyType,
    		@RequestParam(value = "stateOrProvince", required = false) Long stateOrProvinceId,ModelMap modelMap) {    
		
		int sizeNo = 100;
		Integer page = null;
        int pageNumber= page == null ? 0 : page;
        
        if(stateOrProvinceId == 0)
        {
        	 modelMap.addAttribute("policyType", PolicyType.findPolicyTypeByAbbrName(policyType));
        	 modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	 modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
             modelMap.addAttribute("scenarios",Scenario.findScenarioEntriesByPolicyTypeAbbrName(pageNumber*sizeNo, sizeNo,policyType));            
             Long count = Scenario.countScenarios();
             modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        else
        {
        	modelMap.addAttribute("policyType", PolicyType.findPolicyTypeByAbbrName(policyType));
        	modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        	List<Scenario> scenarios = null;
        	scenarios = Scenario.findScenarioEntriesByPolicyTypeAbbrNameAndState(pageNumber*sizeNo, sizeNo,policyType,StateOrProvince.findStateOrProvince(stateOrProvinceId));
            modelMap.addAttribute("scenarios",scenarios);
            Long count = Long.valueOf(scenarios.size());
            modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        
        return "scenario/list";        
    }
	
	@RequestMapping(value = "/scenario/delete/{policyType}/{id}", method = RequestMethod.GET)    
    public String processScenarioDelete(@PathVariable("id") Long id,@PathVariable("policyType") String policyType, @RequestParam(value = "pageNumber", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        LOGGER.error("Deleting:  >>>>>>>>>>>>   "+policyType+"   -  "+id+"   page = "+page+"  size="+size);
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Scenario.class.getSimpleName());
    	log.setOperation("Scenario "+ Scenario.findScenario(id).getName()+" deleted");
    	log.persist();
        
        
        
        Scenario.findScenario(id).remove();
        return "redirect:/scenario/"+policyType+"/list?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
	
	@RequestMapping(value = "/scenario/create_manual/{policyType}", method = RequestMethod.GET)    
    public String renderCreateManual(@PathVariable("policyType") String policyType,ModelMap modelMap, HttpSession session) {    
		modelMap.addAttribute("policyType",PolicyType.findPolicyTypeByAbbrName(policyType));
        modelMap.addAttribute("underwriters",Underwriter.findAllDistinctUnderwriters());
        modelMap.addAttribute("policyForms",PolicyForm.findAllDistinctPolicyForms());
        modelMap.addAttribute("stateOrProvinces",StateOrProvince.findAllStateOrProvinces());
		return "scenario/create_manual";        
    }
	
	@RequestMapping(value = "/scenario/create_wizard/{policyType}", method = RequestMethod.GET)    
    public String renderCreateWizard(@PathVariable("policyType") String policyType,ModelMap modelMap, HttpSession session) {    
		modelMap.addAttribute("policyType",PolicyType.findPolicyTypeByAbbrName(policyType));
        modelMap.addAttribute("all_underwriters",Underwriter.findAllDistinctUnderwriters());
        modelMap.addAttribute("policyForms",PolicyForm.findAllDistinctPolicyForms());
        modelMap.addAttribute("stateOrProvinces",StateOrProvince.findAllStateOrProvinces());
		return "scenario/create_wizard";        
    }
	
	@RequestMapping(value = "/scenario/ajax/add_manual_scenario", method = RequestMethod.GET)    
    public String processManualScenarioAdd(@RequestParam(value="stateOrProvince", required=false) Long stateOrProvince,@RequestParam(value="policyType",required=false) String policyType,@RequestParam(value="name", required=false) String name,ModelMap modelMap, HttpSession session) {    
		AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
		Scenario s = new Scenario();
		
		LOGGER.debug("Adding manual Scenario:  "+name+"  -   "+policyType);
		
		
		s.setStateOrProvince(StateOrProvince.findStateOrProvince(stateOrProvince));
		s.setName(name);
		s.setIsApproved(false);
		s.setPolicyType(PolicyType.findPolicyTypeByAbbrName(policyType));
		s.setCreateUsername(sessionUser.getName());
		s.setUpdateUsername(sessionUser.getName());
		s.setCreateTs(new Date());
		s.setType("manual");
		s.setUpdateTs(new Date());
			
		s.persist();
		
		modelMap.addAttribute("msg",s.getId());
		
		return "scenario/ajax_success";
	}
	
	@RequestMapping(value = "/scenario/ajax/add_scenario", method = RequestMethod.GET)    
    public String processScenarioAdd(@RequestParam(value="stateOrProvince", required=false) Long stateOrProvince,@RequestParam(value="policyType",required=false) String policyType,@RequestParam(value="underwriters", required=false) Long[] uwIds,@RequestParam(value="name", required=false) String name,ModelMap modelMap, HttpSession session) {    

		AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
		
		
		
		List<Underwriter> uwList = new ArrayList<Underwriter>();

		for(Long id : uwIds)
		{
			uwList.add(Underwriter.findUnderwriter(id));
		}
		
		LOGGER.error("Scenario == Null");
			
		Scenario s = new Scenario();
		
		s.setStateOrProvince(StateOrProvince.findStateOrProvince(stateOrProvince));
		s.setName(name);
		s.setIsApproved(false);
		s.setPolicyType(PolicyType.findPolicyTypeByAbbrName(policyType));
		s.setCreateUsername(sessionUser.getName());
		s.setUpdateUsername(sessionUser.getName());
		s.setCreateTs(new Date());
		s.setType("generated");
		s.setUpdateTs(new Date());
			
		s.persist();
			
		LOGGER.error("new id:  "+s.getId());
		
		modelMap.addAttribute("scenario",s);
		modelMap.addAttribute("scenarioId",s.getId());
		modelMap.addAttribute("scenarioName",name);
		modelMap.addAttribute("stateOrProvince",StateOrProvince.findStateOrProvince(stateOrProvince));
		modelMap.addAttribute("rates",Rate.findRatesByStateOrProvince(stateOrProvince));
		modelMap.addAttribute("selected_underwriters",uwList);
		//modelMap.addAttribute("selected_policyForms",pfList);

		//* Now we have to Map the Underwriters and Policy forms
		
		
		
		for(Underwriter uw: uwList)
		{
			
			Underwriter underwriter = new Underwriter();
			underwriter.setDisplayName(uw.getDisplayName());
			underwriter.setImportName(uw.getImportName());
			underwriter.setCreateUsername(null);
			underwriter.setUpdateUsername(null);
			underwriter.setScenario(s);
			underwriter.persist();
			
		}
		
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Scenario.class.getSimpleName());
    	log.setOperation("Scenario "+ s.getName()+" created");
    	log.persist();
    	
    	/*Adding Optional Transaction Questions */
    	
    	LOGGER.error("Transaction Questions Retrieved:  "+s.getStateOrProvince().getTransactionQuestions().size());
    	
    	modelMap.addAttribute("transactionquestions",TransactionQuestion.findTransactionQuestionsForStatesByTypeTransaction(s.getStateOrProvince()));
    	modelMap.addAttribute("policyquestions",TransactionQuestion.findTransactionQuestionsForStatesByTypePolicy(s.getStateOrProvince()));
    	
    	modelMap.addAttribute("policyforms",StateOrProvince.findStateOrProvince(stateOrProvince).getPolicyForms());
    	//modelMap.addAttribute("transactionquestions",s.getStateOrProvince().getTransactionQuestions());

        return "scenario/create_group_form";        
    }
	
	@RequestMapping(value = "/scenario/ajax/get_groups/{id}", method = RequestMethod.POST)      
    public String getTrialGroups(@PathVariable("id") Long scenarioId,ModelMap modelMap,HttpSession session) 
	{
		
		Scenario scenario = Scenario.findScenario(scenarioId);
		
		modelMap.addAttribute("scenario",scenario);
		modelMap.addAttribute("trialgroups",scenario.getTrialGroups());
		
		List<String> selectedUwList = new ArrayList<String>();
		
		for(TrialGroup tg: scenario.getTrialGroups())
		{
			String selecteduw = "";
			for(Underwriter uw : tg.getUnderwriters())
	        {
	        	selecteduw = selecteduw+" "+uw.getDisplayName();
	        }
			selectedUwList.add(selecteduw);
		}
		
		List<String> selectedPfList = new ArrayList<String>();
		
		for(TrialGroup tg: scenario.getTrialGroups())
		{
			String selectedpf = "";
			for(PolicyForm pf : tg.getPolicyForms())
	        {
	        	selectedpf = selectedpf+" "+pf.getDisplayName();
	        }
			selectedPfList.add(selectedpf);
		}
		
		modelMap.addAttribute("transactionquestions",TransactionQuestion.findTransactionQuestionsForStatesByTypeTransaction(scenario.getStateOrProvince()));
    	modelMap.addAttribute("policyquestions",TransactionQuestion.findTransactionQuestionsForStatesByTypePolicy(scenario.getStateOrProvince()));
		modelMap.addAttribute("selectedUwList",selectedUwList);
		modelMap.addAttribute("selectedPfList",selectedPfList);
		
		return "scenario/update_group_form";
	}
	
	@RequestMapping(value = "/scenario/ajax/update_show/{id}", method = RequestMethod.POST)    
    public String renderScenarioUpdateShow(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("scenario", Scenario.findScenario(id));        
        return "scenario/update_show";        
    }
	
	@RequestMapping(value = "/scenario/ajax/update_scenario", method = RequestMethod.GET)    
    public String processScenarioUpdate(@RequestParam(value="scenarioId", required=false) Long scenarioId,@RequestParam(value="stateOrProvince", required=false) Long stateOrProvince,@RequestParam(value="policyType",required=false) String policyType,@RequestParam(value="underwriters", required=false) Long[] uwIds,@RequestParam(value="name", required=false) String name,ModelMap modelMap, HttpSession session) {    
		
		//Remove the Old Scenario First
		LOGGER.error("removing old Scenario:  "+scenarioId);
		Scenario.findScenario(scenarioId).remove();
		
		
		AppUser sessionUser = WebappUtils.getAuthenticationObject(session);

		
		List<Underwriter> uwList = new ArrayList<Underwriter>();

		for(Long id : uwIds)
		{
			uwList.add(Underwriter.findUnderwriter(id));
		}
		
		LOGGER.error("Creating New Scenario");
			
		Scenario s = new Scenario();
		
		LOGGER.error("State:  "+stateOrProvince);
		LOGGER.error("Name:  "+name);
		LOGGER.error("Name:  "+policyType);
		
		s.setStateOrProvince(StateOrProvince.findStateOrProvince(stateOrProvince));
		s.setName(name);
		s.setIsApproved(false);
		s.setPolicyType(PolicyType.findPolicyTypeByAbbrName(policyType));
		s.setCreateUsername(sessionUser.getName());
		s.setUpdateUsername(sessionUser.getName());
		s.setCreateTs(new Date());
		s.setUpdateTs(new Date());
			
		s.persist();
			
		LOGGER.error("new id:  "+s.getId());
	
		modelMap.addAttribute("scenarioId",s.getId());
		modelMap.addAttribute("scenarioName",name);
		modelMap.addAttribute("stateOrProvince",StateOrProvince.findStateOrProvince(stateOrProvince));
		modelMap.addAttribute("rates",Rate.findRatesByStateOrProvince(stateOrProvince));
		modelMap.addAttribute("selected_underwriters",uwList);

		//* Now we have to Map the Underwriters and Policy forms

		for(Underwriter uw: uwList)
		{
			
			Underwriter underwriter = new Underwriter();
			underwriter.setDisplayName(uw.getDisplayName());
			underwriter.setImportName(uw.getImportName());
			underwriter.setCreateUsername(null);
			underwriter.setUpdateUsername(null);
			underwriter.setScenario(s);
			underwriter.persist();
			
		}
	
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Scenario.class.getSimpleName());
    	log.setOperation("Scenario "+ s.getName()+" Updated");
    	log.persist();
    	
    	/*Adding Optional Transaction Questions */
    	
    	LOGGER.error("Transaction Questions Retrieved:  "+s.getStateOrProvince().getTransactionQuestions().size());
    	
    	modelMap.addAttribute("transactionquestions",s.getStateOrProvince().getTransactionQuestions());

        return "scenario/create_group_form";        
    }
	
	@RequestMapping(value = "/scenario/ajax/get_transactionquestions/{id}", method = RequestMethod.GET)      
    public String getTransactionQuestions(@PathVariable("id") Long stateId,ModelMap modelMap,HttpSession session) 
	{
		List<TransactionQuestion> tqList = StateOrProvince.findStateOrProvince(stateId).getTransactionQuestions();
		modelMap.addAttribute("transactionquestions", tqList); 
		return "scenario/ajax_transaction_question_list"; 
	}
	
	@RequestMapping(value = "/scenario/ajax/get_policyforms/{id}", method = RequestMethod.GET)      
    public String getPolicyForms(@PathVariable("id") Long stateId,ModelMap modelMap,HttpSession session) 
	{
		Set<PolicyForm> pfList = StateOrProvince.findStateOrProvince(stateId).getPolicyForms();
		modelMap.addAttribute("policyForms", pfList); 
		return "scenario/ajax_policyform_list"; 
	}
	@RequestMapping(value = "/scenario/ajax/get_policyforms_classonly/{id}", method = RequestMethod.GET)      
    public String getPolicyFormsClassOnly(@PathVariable("id") Long stateId,ModelMap modelMap,HttpSession session) 
	{
		Set<PolicyForm> pfList = StateOrProvince.findStateOrProvince(stateId).getPolicyForms();
		modelMap.addAttribute("policyForms", pfList); 
		return "scenario/ajax_policyform_list_classonly"; 
	}
	
	@RequestMapping(value = "/scenario/ajax/approve/{id}", method = RequestMethod.POST)    
    public String processScenarioApprove(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        Scenario s = Scenario.findScenario(id);
        s.setIsApproved(true);
        s.merge();

        modelMap.addAttribute("msg","1");  
		return "scenario/ajax_success";       
    }
	
	@RequestMapping(value = "/scenario/ajax/download/{id}", method = RequestMethod.GET)    
    public void processScenarioAjaxDownload(@PathVariable("id") Long id, ModelMap modelMap,HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{    
        
		LOGGER.error("Downloading Scenario");
		
		if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        Scenario scenario = Scenario.findScenario(id);
        scenario.setIsApproved(true);
        scenario.merge();
        
        //WritableWorkbook importDoc = ImportBuilder.generateImportDoc(scenario);
        
        LOGGER.error("Scenario:  "+scenario.getName());
        
        OutputStream os = null;
        
        try {
        	
        	LOGGER.error("Creating Workbook");
        	response.setContentType("application/vnd.ms-excel");
        	response.setHeader("Content-Disposition", "attachment; filename="+scenario.getName()+".xls");
        	
        	os=response.getOutputStream();
        	WritableWorkbook workbook = Workbook.createWorkbook(os);
        	
        	WritableSheet overviewSheet = workbook.createSheet("Overview", 0);
    		WritableSheet testCaseSheet = workbook.createSheet("TestCase", 1);
    		WritableSheet transactionQuestionSheet = workbook.createSheet("TransactionQuestions", 2);
    		WritableSheet policiesSheet = workbook.createSheet("Policies", 3);
    		WritableSheet policyQuestionSheet = workbook.createSheet("PolicyQuestions", 4);
    		
    		workbook.write();
    		workbook.close();
        }
        catch (Exception e){
        	   throw new ServletException("Exception in Excel Sample Servlet", e);
        } 
        finally{
        	try
            {
                  os.flush();
            }
            catch (Exception e)
            { LOGGER.error("Failure to Flush OutputStreem:  ",e);}
            try
            {
                  os.close();
            }
            catch (Exception e)
            {LOGGER.error("Failure to Close OutputStreem:  ",e);}
        }//End Finally

        //modelMap.addAttribute("msg","1");  
		//return "scenario/ajax_success";       
    }
	
	@RequestMapping(value = "/scenario/download/{id}", method = RequestMethod.GET)    
    public void processScenarioDownload(@PathVariable("id") Long id, ModelMap modelMap,HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{    
        
		LOGGER.error("Downloading Scenario");
		
		if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        Scenario scenario = Scenario.findScenario(id);
        scenario.setIsApproved(true);
        scenario.merge();
        
        ImportBuilder.generateImportDoc(scenario,response);
  
    }


	@RequestMapping(value = "/scenario", method = RequestMethod.POST)    
    public String create(@Valid Scenario scenario, BindingResult result, ModelMap modelMap) {    
        if (scenario == null) throw new IllegalArgumentException("A scenario is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("scenario", scenario);            
            modelMap.addAttribute("policyforms", PolicyForm.findAllPolicyForms());            
            modelMap.addAttribute("policytypes", PolicyType.findAllPolicyTypes());            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());            
            return "scenario/create";            
        }        
        scenario.persist();        
        return "redirect:/scenario/" + scenario.getId();        
    }

	@RequestMapping(value = "/scenario/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("scenario", new Scenario());        
        modelMap.addAttribute("policyforms", PolicyForm.findAllPolicyForms());        
        modelMap.addAttribute("policytypes", PolicyType.findAllPolicyTypes());        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());        
        return "scenario/create";        
    }

	@RequestMapping(value = "/scenario/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("scenario", Scenario.findScenario(id));
        
        String url = "scenario/show";
        
        if(Scenario.findScenario(id).getType().equalsIgnoreCase("manual"))
        {
        	url = "scenario/manual_show";
        }
        
        return url;        
    }

	@RequestMapping(value = "/scenario", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("scenarios", Scenario.findScenarioEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) Scenario.countScenarios() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
        }        
        return "scenario/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid Scenario scenario, BindingResult result, ModelMap modelMap) {    
        if (scenario == null) throw new IllegalArgumentException("A scenario is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("scenario", scenario);            
            modelMap.addAttribute("policyforms", PolicyForm.findAllPolicyForms());            
            modelMap.addAttribute("policytypes", PolicyType.findAllPolicyTypes());            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());            
            return "scenario/update_wizard";            
        }        
        scenario.merge();        
        return "redirect:/scenario/" + scenario.getId();        
    }

	@RequestMapping(value = "/scenario/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("scenario", Scenario.findScenario(id));        
        modelMap.addAttribute("policyForms", StateOrProvince.findStateOrProvince(Scenario.findScenario(id).getStateOrProvince().getId()).getPolicyForms());        
        modelMap.addAttribute("policytypes", PolicyType.findAllPolicyTypes());        
        modelMap.addAttribute("stateOrProvinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("all_underwriters", Underwriter.findAllDistinctUnderwriters());
        modelMap.addAttribute("transactionQuestions", StateOrProvince.findStateOrProvince(Scenario.findScenario(id).getStateOrProvince().getId()).getTransactionQuestions());
        
        String selecteduw = "";
        for(Underwriter uw : Scenario.findScenario(id).getUnderwriters())
        {
        	selecteduw = selecteduw+" "+uw.getDisplayName();
        }
        
        modelMap.addAttribute("selecteduw",selecteduw);
        
        String url = "scenario/update_wizard";
        
        if(Scenario.findScenario(id).getType().equalsIgnoreCase("manual"))
        {
        	url = "scenario/manual_update";
        }

        return url;        
    }

	@RequestMapping(value = "/scenario/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        Scenario.findScenario(id).remove();        
        return "redirect:/scenario?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
	
	@RequestMapping(value = "/scenario/ajax/{id}", method = RequestMethod.DELETE)    
    public String ajaxDelete(@PathVariable("id") Long id) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        LOGGER.debug("Deleting Scenario:  "+id);
        Scenario.findScenario(id).remove();        
        return "scenario/ajax_success";
    }
}
